package cn.flying.base.core.handler;

import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.flying.base.common.enums.RtCodeEnum;
import cn.flying.base.common.exception.BizException;
import cn.flying.base.common.exception.FlyingException;
import cn.flying.base.common.exception.RpcException;
import cn.flying.base.common.vo.Rt;


/**
 * @description: 全局异常处理
 * @author: lvyong
 * @date: 2022年04月02日 22:06
 * @version: 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Rt bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("业务处理异常！原因是：{}", e.getMessage());
        return Rt.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = RpcException.class)
    @ResponseBody
    public Rt rpcExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("rpc调用异常！原因是：{}", e.getMessage());
        return Rt.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理自定义的公共异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = FlyingException.class)
    @ResponseBody
    public Rt flyingExceptionHandler(HttpServletRequest req, FlyingException e) {
        logger.error("系统处理异常！原因是：{}", e.getMessage());
        return Rt.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验绑定异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Rt bindExceptionHandler(HttpServletRequest req, BindException e) {
        logger.error("参数校验异常！原因是:", e.getMessage());
        List<FieldError> fieldErrors = e.getFieldErrors();
        Map<String, String> errorMap = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return Rt.error(RtCodeEnum.R_ERROR);
    }

    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Rt exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("系统未知异常！原因是:", e);
        return Rt.error(RtCodeEnum.R_ERROR);
    }
}
